<template>
  <Dialog
    :title="t('interviewSlot.change.title')"
    v-model="dialogVisible"
    width="500"
    :fullscreen="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('student.fields.interviewDate')" prop="interviewId">
        <el-date-picker
          class="!w-1/1"
          v-model="formData.interviewDate"
          type="date"
          value-format="x"
          :placeholder="t('common.selectTextPlaceholder') + t('student.fields.interviewDate')"
          :disabled-date="disableInterviewDate"
          @change="getGroupsSpecificDate"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item :label="t('student.fields.interviewGroupId')" prop="interviewGroupId">
        <el-select
          v-model="formData.interviewGroupId"
          :placeholder="t('common.selectTextPlaceholder') + t('student.fields.interviewGroupId')"
          v-loading="groupLoading"
          element-loading-custom-class="small-loading-icon"
          @change="getSlotSpecificGroup"
          :clearable="false"
        >
          <el-option
            v-for="item in groups"
            :key="item.id"
            :label="item.groupName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('student.fields.interviewSlotTime')" prop="interviewSlotId">
        <el-select
          v-model="formData.interviewSlotId"
          :placeholder="t('common.selectTextPlaceholder') + t('student.fields.interviewSlotTime')"
          v-loading="slotLoading"
          element-loading-custom-class="small-loading-icon"
          @change="slotChange"
          :clearable="false"
        >
          <el-option
            v-for="item in slots"
            :key="item.id"
            :label="`${item.startTime}-${item.endTime}`"
            :value="item.id"
            :disabled="item.disabled"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
/** 修改面试时间组件 */
import { StudentApi, StudentVO } from '@/api/recruit/recruitstudent'
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import { formatDate } from '@/utils/formatTime'
import { InterviewGroupApi, InterviewGroupVO } from '@/api/recruit/interviewgroup'
import { ElSelect, FormRules } from 'element-plus'
import { InterviewSlotApi, InterviewSlotAvailableListRespVO } from '@/api/recruit/interviewslot'

defineOptions({ name: 'ChangeStudentInterviewSlot' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const dialogVisible = ref(false)
const formLoading = ref(false)

const disableInterviewDate = (time: Date) => {
  if (currentBatch.value) {
    // 处于currentBatch.value.recruitStartTime 和 currentBatch.value.recruitEndTime之外的日期不可选
    const startTime = new Date(currentBatch.value.recruitStartTime)
    const endTime = new Date(currentBatch.value.recruitEndTime)
    // 将 startTime 的时间设置为该日的开始
    startTime.setHours(0, 0, 0, 0)
    // 将 endTime 的时间设置为该日的结束
    endTime.setHours(23, 59, 59, 999)
    return time < startTime || time > endTime
  } else {
    // 如果没有选择计划，则所有日期都不可选
    return true
  }
}

const formData = ref<StudentVO>({} as StudentVO)
const formRules = reactive<FormRules>({
  interviewId: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('student.fields.interviewDate'),
      trigger: 'change'
    }
  ],
  interviewGroupId: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('student.fields.interviewGroupId'),
      trigger: 'change'
    }
  ],
  interviewSlotId: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('student.fields.interviewSlotTime'),
      trigger: 'change'
    }
  ]
})
const currentBatch = ref<BatchVO>({} as BatchVO)
// 显示修改窗口
const open = async (id: string) => {
  formData.value = {} as StudentVO
  groups.value = []
  slots.value = []

  dialogVisible.value = true
  formLoading.value = true
  formData.value = await StudentApi.getStudent(id)
  currentBatch.value = await BatchApi.getBatch(formData.value.batchId)
  const api = []
  if (formData.value.interviewDate) {
    api.push(getGroupsSpecificDate(formData.value.interviewDate, false))
  }
  if (formData.value.interviewGroupId) {
    api.push(getSlotSpecificGroup(formData.value.interviewGroupId, false))
  }
  await Promise.all(api)
  formLoading.value = false
}

const groups = ref<InterviewGroupVO[]>([])
const groupLoading = ref(false)
// 选择某一日后查询该日的面试组
const getGroupsSpecificDate = async (date: number, clearField = true) => {
  groupLoading.value = true
  const str = formatDate(date, 'YYYY-MM-DD')
  groups.value = await InterviewGroupApi.listByDate(str)
  groupLoading.value = false
  if (clearField) {
    // 清空之前选择的组和时间段
    formData.value.interviewId = undefined as any
    formData.value.interviewGroupId = undefined as any
    formData.value.interviewSlotId = undefined as any
  }
}

const slots = ref<InterviewSlotAvailableListRespVO[]>([])
const slotLoading = ref(false)
// 选择某一组后查询该组的面试时间段
const getSlotSpecificGroup = async (groupId: string, clearField = true) => {
  slotLoading.value = true
  slots.value = await InterviewSlotApi.getInterviewSlotAvailableInfoList(groupId)
  slotLoading.value = false

  if (clearField) {
    // 根据groupId找到对应的面试ID
    const group = groups.value.find((item) => item.id === groupId)
    if (group) {
      // 选组才有日期ID 才能通过校验
      formData.value.interviewId = group.interviewId
    } else {
      formData.value.interviewId = undefined as any
    }

    formData.value.interviewSlotId = undefined as any
  }
}

const slotChange = () => {
  if (formData.value.interviewSlotId) {
    const slot = slots.value.find((item) => item.id === formData.value.interviewSlotId)
    if (slot) {
      formData.value.interviewSlotTime = `${slot.startTime}-${slot.endTime}`
    }
  } else {
    formData.value.interviewSlotTime = ''
  }
}

const emit = defineEmits(['success'])

const formRef = ref() // 表单 Ref
const submitForm = async () => {
  try {
    // 校验表单
    await formRef.value.validate()
  } catch {
    return
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StudentVO
    data.interviewSelected = true
    // 主流程状态
    data.stage = '预约完成'
    await StudentApi.updateStudent(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

defineExpose({ open })
</script>

<style scoped lang="scss"></style>
